﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.StorageClient;
using Microsoft.WindowsAzure.ServiceRuntime;
using System.Configuration;
using System.Data.Services.Client;
using System.Diagnostics;

namespace PC.AzureMultiApp.Storage
{
    public class CounterDataSource
    {
        StorageContext context;

        public CounterDataSource()
        {
            CloudStorageAccount.SetConfigurationSettingPublisher((configName, configSetter) =>
            {
                if (RoleEnvironment.IsAvailable)
                    configSetter(RoleEnvironment.GetConfigurationSettingValue(configName));
                else
                    configSetter(ConfigurationManager.AppSettings[configName]);
            });


            var sa = CloudStorageAccount.FromConfigurationSetting("azuremultiappstorage");

            this.context = new StorageContext(sa.TableEndpoint.ToString(), sa.Credentials);

            var ctc = sa.CreateCloudTableClient();

            ctc.CreateTableIfNotExist(GlobalDef.TableName);
        }

        public void Clear()
        {
            foreach (var item in this.context.Counters)
                this.context.DeleteObject(item);
            this.context.SaveChanges();
        }


        public IEnumerable<AzureCounterEntity> GetCounters()
        {
            // See Yi-Lun Luo  - http://social.msdn.microsoft.com/Forums/en/windowsazure/thread/7ce8f642-6566-426c-8beb-7f29e66189d0
            DateTime now = DateTime.UtcNow;
            DateTime fiveMinutesAgo = now.AddMinutes(-5);
            string partitionKeyNow = string.Format("0{0}", now.Ticks.ToString());
            string partitionKeyFiveMinutesAgo = string.Format("0{0}", fiveMinutesAgo.Ticks.ToString());

            var query = (from c in this.context.Counters
                         where
                            c.PartitionKey.CompareTo(partitionKeyNow) < 0
                            &&
                            c.PartitionKey.CompareTo(partitionKeyFiveMinutesAgo) > 0
                         select c).Take(200).AsTableServiceQuery<AzureCounterEntity>();

            List<AzureCounterEntity> performanceCountersEntitiesList = null;
            try
            {
                performanceCountersEntitiesList = query.Execute().ToList<AzureCounterEntity>();
            }
            catch (DataServiceQueryException ex)
            {
                Trace.TraceError(ex.Message);

                // Swallow error from attempt to query WadPerformanceCountersTable before the Diagnostics Agent creates it.
            }

            return performanceCountersEntitiesList;
        }
    }
}
